# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : 客户端（RPC Client）.py
# @Author: dongguangwen
# @Date  : 2025-04-12 12:23
import pika
import uuid

credentials = pika.PlainCredentials('admin', 'password')


class FibonacciRpcClient:
    def __init__(self):
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters('192.168.1.119', credentials=credentials, virtual_host='my_vhost'))
        self.channel = self.connection.channel()

        # 创建一个临时队列，用于接收返回结果
        result = self.channel.queue_declare(queue='', exclusive=True)
        self.callback_queue = result.method.queue

        self.channel.basic_consume(
            queue=self.callback_queue,
            on_message_callback=self.on_response,
            auto_ack=True
        )

        self.response = None
        self.corr_id = None

    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = body

    def call(self, n):
        self.response = None
        self.corr_id = str(uuid.uuid4())  # 唯一标识符
        self.channel.basic_publish(
            exchange='',
            routing_key='rpc_queue',
            properties=pika.BasicProperties(
                reply_to=self.callback_queue,
                correlation_id=self.corr_id
            ),
            body=str(n)
        )

        while self.response is None:
            self.connection.process_data_events()  # 等待响应
        return int(self.response)


# 调用
rpc = FibonacciRpcClient()
print("[⏱] 请求 fib(10)")
result = rpc.call(10)
print(f"[✅] 返回结果：{result}")
